/*
 * @Descripttion:
 * @version:
 * @Author: ChenXiang
 * @Date: 2021-07-24 22:52:52
 * @LastEditors: ChenXiang
 * @LastEditTime: 2021-08-19 13:48:46
 */
import React from "react";
import FieldContext from "./FieldContext";
export default class Field extends React.Component {
  static contextType = FieldContext;
  onStoreChange = () => {
    this.forceUpdate();
  };

  componentDidMount() {
    // 实例放到form表单里
    const { registerEntity } = this.context;
    this.cancelRegiter = registerEntity(this);
  }

  componentWillUnmount() {
    // 取消注册
    if (this.cancelRegiter) {
      this.cancelRegiter();
    }
  }

  onFinish = (val) => {
    console.log("onFinish", val);
  };

  getControlled = () => {
    const { name } = this.props;
    const { getFieldValue, setFieldValue } = this.context;
    return {
      value: getFieldValue(name),
      onChange: (event) => {
        const target = event.target.value;
        setFieldValue({
          [name]: target
        });
      }
    };
  };

  render() {
    const { children } = this.props;
    // clone后对组件进行更改，例如添加onchange
    const returnChildNode = React.cloneElement(children, this.getControlled());
    return returnChildNode;
  }
}
